import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base/net/http_request.dart';
import 'package:oktoast/oktoast.dart';

const BaseUrl = "";

class DioClient {
  static Dio _dio;
  static var header = {};

  static initDio() {
    var baseOption = BaseOptions(
        baseUrl: BaseUrl,
        headers: header,
        responseType: ResponseType.json,
        receiveTimeout: 3000);
    _dio = Dio(baseOption);
  }

  Future<HttpRequest<T>> httpRequest<T>(String api,
      {String method = "GET",
      ProgressCallback onReceiveCallBack,
      ProgressCallback onSendCallBack,
      Map<String, dynamic> params,
      bool showLoading=true,
      Widget loadingWidget}) async {
    if (_dio == null) {
      initDio();
    }
    var httpRequest = HttpRequest();
    if (showLoading) {
      showToastWidget(
          loadingWidget == null ? CircularProgressIndicator() : loadingWidget,
          duration: Duration(seconds: 60));
    }
    try{
      var response = await _dio.request<T>(api,
          options: Options(
            method: method,
          ),
          queryParameters: params,
          onReceiveProgress: onReceiveCallBack,
          onSendProgress: onSendCallBack);
      if (response.statusCode == 200) {
        dismissAllToast();
        httpRequest.data = response.data;
        httpRequest.isSuccess = true;
        httpRequest.msg = "请求成功";
        return httpRequest;
      }else if (response.statusCode >= 500 && response.statusCode <= 599) {
        httpRequest.isSuccess = false;
        httpRequest.msg = "服务器出错，statusCode:${response.statusCode}";
        return httpRequest;
      } else if (response.statusCode >= 400 && response.statusCode <= 499) {
        httpRequest.isSuccess = false;
        httpRequest.msg = "接口请求出错，statusCode:${response.statusCode}";
        return httpRequest;
      } else if (response.statusCode >= 300 && response.statusCode <= 399) {
        httpRequest.isSuccess = false;
        httpRequest.msg = "接口重定向，statusCode:${response.statusCode}";
        return httpRequest;
      }

    }catch(e){

    }

    return httpRequest;
  }
}
